/**
 * Copyright (C) 2010 Hamburg Sud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hamburgsud.log4testing.core.output.util;

import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import com.hamburgsud.log4testing.core.data.TestObject;
import com.hamburgsud.log4testing.core.output.writer.VelocityWriter;

public class Velocity {

	final private static Logger logger = Logger.getLogger(Velocity.class);

	private VelocityWriter<?> writer;
	private VelocityEngine engine;

	private Velocity() {
		super();
	}

	public Velocity(final VelocityWriter<?> velocityWriter) {
		this();
		this.writer = velocityWriter;
	}

	public String merge(final TestObject testObject) {
		final StringWriter w = new StringWriter();
		final String templateFileName = writer.getTemplate();
		try {
			final VelocityEngine ve = getEngine();
			final Template template = ve.getTemplate(templateFileName);
			template.merge(getContext(testObject), w);
		} catch (Exception e) {
			logger.error(
					"Problem while merging an test object with the template "
							+ templateFileName + ".", e);
		}
		return w.toString();
	}

	private VelocityContext getContext(final TestObject testObject) {
		final VelocityContext context = new VelocityContext();
		context.put(writer.getVariable(), testObject);
		return context;
	}

	private VelocityEngine getEngine() throws Exception {
		if (engine == null) {
			engine = new VelocityEngine();
			engine.setProperty("file.resource.loader.class",
					ClasspathResourceLoader.class.getName());
			engine.setProperty("eventhandler.include.class",
					"org.apache.velocity.app.event.implement.IncludeRelativePath");
			engine.init();
		}
		return engine;
	}

}
